package br.ufrgs.tcp.db;

import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import br.ufrgs.tcp.model.IModel;

public abstract  class SQLAdapter {

	private Context context;
	private SQLiteDatabase database;
	private AppSQLHelper dbHelper;

	public SQLAdapter(Context context) {
		this.context = context;
	}

	public SQLAdapter open() throws SQLException {
		dbHelper = new AppSQLHelper(context);
		try {
			database = dbHelper.getWritableDatabase();		
		} catch (SQLiteException e) {
			Log.i("SQLAdapter", "Tentativa de abrir um database ja previamente aberto");
		}
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public <T extends IModel> void bulkSave(List<T> data) {
		database.beginTransaction();
		for (T singleData : data) 
			database.insert(getTableName(), null, createContentValues(singleData));	
		database.setTransactionSuccessful();	
		database.endTransaction();
	}

	protected abstract <T extends IModel> ContentValues createContentValues(T data);
	protected abstract String getTableName();
	protected abstract String[] getColumns();

	public void deleteAll() {
		database.delete(getTableName(), null, null);
		
	}

	public Cursor fetchAll() {
		return database.query(getTableName(), AppSQLHelper.PREDIO_COLUMNS, null, null, null, null, null);
	}

	public void bulkInsert(List<? extends IModel> data) {
		database.beginTransaction();
		
		for (IModel singleData : data) {
			database.insert(getTableName(),null, createContentValues(singleData));
		}
		database.setTransactionSuccessful();
		database.endTransaction();
	}

	public Cursor fetchByNumero(String text) {
		return database.query(getTableName(), getColumns(), "NUMERO LIKE ?", new String[] {  "%" + text + "%" }, null, null, null);
	}

	

}
